import { QXEvent } from 'qx-util';
import { ICell, IEventName } from '../../interface';
import { getDateStr, getDateStrFull, differDateDay, generateCells } from '../../utils';

/**
 * 日历组件总控制器
 *
 * @export
 * @class IbzExpCalendarController
 */
export class IbzExpCalendarController {
  /**
   * 最大时间跨度
   *
   * @type {number}
   * @memberof IbzExpCalendarController
   */
  maxTimeSpan: number;

  /**
   * 起始日期
   *
   * @type {string} YYYY-MM-DD
   * @memberof IbzExpCalendarController
   */
  startDate: string;

  /**
   * 结束日期
   *
   * @type {string} YYYY-MM-DD
   * @memberof IbzExpCalendarController
   */
  endDate: string;

  /**
   * 日期内的数据量
   *
   * @type {*}
   * @memberof IbzExpCalendarController
   */
  data: any;

  /**
   * 自动填充模式
   *
   * @type {*}
   * @memberof IbzExpCalendarController
   */
  autoComplete: boolean;

  /**
   *自动填充天数
   *
   * @type {number | string}
   * @memberof IbzExpCalendarController
   */
  completeDays: number | string;

  /**
   * 事件
   *
   * @type {QXEvent<''>}
   * @memberof IbzExpCalendarController
   */
  evt: QXEvent<IEventName>;

  /**
   * 当前Date对象
   *
   * @type {*}
   * @memberof IbzExpCalendarController
   */
  currentDate: Date;

  /**
   * 单元格（显示多少日）一个月最多31天，所以最多6行表格，6*7=42
   *
   * @type {any[]}
   * @memberof IbzExpCalendarController
   */
  cells: ICell[] = new Array(42);

  /**
   * 日历组件标题
   *
   * @type {string}
   * @memberof IbzExpCalendarController
   */
  title: string = '';

  /**
   * 主题
   *
   * @type {string}
   * @memberof IbzExpCalendarController
   */
  theme: string = '';

  /**
   * 尺寸
   *
   * @type {string}
   * @memberof IbzExpCalendarController
   */
  size: string = '';

  /**
   * 选中数据
   *
   * @type {ICell[]}
   * @memberof IbzExpCalendarController
   */
  selections: ICell[] = [];

  /**
   * 初始化控制器参数
   *
   * @param {number} maxTimeSpan
   * @param {(string | null)} startDate
   * @param {(string | null)} endDate
   * @param {*} data
   * @memberof IbzExpCalendarController
   */
  initCtrlParam(
    maxTimeSpan: number,
    startDate: string | null,
    endDate: string | null,
    data: any,
    complete: boolean,
    completeDays: string | number,
    theme: string,
    size: string,
  ) {
    this.maxTimeSpan = maxTimeSpan;
    this.startDate = startDate;
    this.endDate = endDate;
    this.data = data;
    this.autoComplete = complete;
    this.completeDays = completeDays;
    this.theme = theme;
    this.size = size;
    this.cells.fill({ value: '0', class: 'cell-default', date: '' });
  }

  /**
   * 上个月
   *
   * @memberof IbzExpCalendarController
   */
  previousMonth() {
    this.currentDate.setMonth(this.currentDate.getMonth() - 1);
    this.evt.emit('changeDate');
  }

  /**
   * 下个月
   *
   * @memberof IbzExpCalendarController
   */
  nextMonth() {
    this.currentDate.setMonth(this.currentDate.getMonth() + 1);
    this.evt.emit('changeDate');
  }

  /**
   * 上一年
   *
   * @memberof IbzExpCalendarController
   */
  previousYear() {
    this.currentDate.setFullYear(this.currentDate.getFullYear() - 1);
    this.evt.emit('changeDate');
  }

  /**
   * 下一年
   *
   * @memberof IbzExpCalendarController
   */
  nextYear() {
    this.currentDate.setFullYear(this.currentDate.getFullYear() + 1);
    this.evt.emit('changeDate');
  }

  /**
   * 今天
   *
   * @memberof IbzExpCalendarController
   */
  today() {
    this.currentDate = new Date();
    this.evt.emit('changeDate');
  }

  /**
   * 选择日期
   *
   * @param {*} cell
   * @memberof IbzExpCalendarController
   */
  seletDate(cell: ICell) {
    if (this.startDate === cell.date) {
      return;
    }

    if (this.autoComplete) {
      this.autoCompleteDate(cell);
    } else {
      this.manulCompleteDate(cell);
    }
    this.setCurrentDay(cell.date);
  }

  /**
   * 设置当前日期
   *
   * @param {string} date
   * @memberof IbzExpCalendarController
   */
  setCurrentDay(date: string) {
    const cellDate = new Date(date);
    this.currentDate.setMonth(cellDate.getMonth());
    this.currentDate.setFullYear(cellDate.getFullYear());
    this.setCells();
    this.evt.emit('selectChange');
  }

  /**
   *自动填充选择日期
   *
   * @param {ICell} cell
   * @memberof IbzExpCalendarController
   */
  autoCompleteDate(cell: ICell) {
    if (!cell.date) {
      let startArr = new Date().toLocaleDateString().split('/');
      startArr = startArr.map((item: any) => {
        if (item < 10 && item > 0) {
          item = '0' + item;
        }
        return item;
      });
      this.startDate = startArr.join('-');
    }
    this.startDate = cell.date;
    const startDate = new Date(this.startDate);
    if (this.completeDays < 1) {
      this.completeDays = 1;
    } else if (this.completeDays > 13) {
      this.completeDays = 13;
    }
    startDate.setDate(startDate.getDate() + Number(this.completeDays));
    const endDate = startDate;
    let endArr = endDate.toLocaleDateString().split('/');
    endArr = endArr.map((item: any) => {
      if (item < 10 && item > 0) {
        item = '0' + item;
      }
      return item;
    });
    this.endDate = endArr.join('-');
  }

  /**
   *手动填充选择日期
   *
   * @param {ICell} cell
   * @memberof IbzExpCalendarController
   */
  manulCompleteDate(cell: ICell) {
    const cellDate = new Date(cell.date);
    if (!this.startDate) {
      this.startDate = cell.date;
    } else {
      const startDate = new Date(this.startDate);
      if (this.endDate) {
        // 已选中结束节点时
        const endDate = new Date(this.endDate);
        if (cellDate < startDate) {
          if (differDateDay(cell.date, this.endDate) + 1 > this.maxTimeSpan) {
            cellDate.setDate(cellDate.getDate() + this.maxTimeSpan - 2);
            this.endDate = getDateStrFull(cellDate);
          }
          this.startDate = cell.date;
        } else if (cellDate > startDate && cellDate < endDate) {
          this.endDate = cell.date;
        } else {
          if (differDateDay(cell.date, this.startDate) + 1 > this.maxTimeSpan) {
            cellDate.setDate(cellDate.getDate() - this.maxTimeSpan + 2);
            this.startDate = getDateStrFull(cellDate);
          }
          this.endDate = cell.date;
        }
      } else {
        // 未选中结束节点时
        if (cellDate < startDate) {
          this.endDate = this.startDate;
          if (differDateDay(cell.date, this.startDate) + 1 > this.maxTimeSpan) {
            cellDate.setDate(startDate.getDate() - this.maxTimeSpan + 1);
            this.startDate = getDateStrFull(cellDate);
          } else {
            this.startDate = cell.date;
          }
        } else {
          if (differDateDay(cell.date, this.startDate) + 1 > this.maxTimeSpan) {
            cellDate.setDate(startDate.getDate() + this.maxTimeSpan - 1);
            this.endDate = getDateStrFull(cellDate);
          } else {
            this.endDate = cell.date;
          }
        }
      }
    }
  }

  /**
   * 改变选中区间颜色
   *
   * @memberof IbzExpCalendarController
   */
  selectionChange() {
    const selections: ICell[] = [];
    if (this.startDate && this.endDate) {
      const startDate = new Date(this.startDate);
      const endDate = new Date(this.endDate);
      this.cells.forEach((cell: ICell) => {
        const date = new Date(cell.date);
        if (date >= startDate && date <= endDate) {
          selections.push(cell);
        }
      });
    } else if (this.startDate) {
      const startDateCell = this.cells.find((cell: ICell) => {
        if (cell.date === this.startDate) {
          return cell;
        }
      });
      selections.push(startDateCell);
    }
    this.selections = selections;
    this.computeRangeColor();
  }

  /**
   *计算改变颜色cell
   *
   * @memberof IbzExpCalendarController
   */
  computeRangeColor() {
    if (this.selections.length === 0) {
      return;
    }
    this.cells.forEach((cell: ICell) => {
      const index: number = this.selections.findIndex(select => cell.date === select.date);
      if (index !== -1) {
        let cellClass: string = '';
        if (cell.date === this.startDate) {
          if (cell.class === 'cell-today') {
            cellClass += 'cell-today ';
          }
          cellClass += 'start-section';
        } else if (cell.date === this.endDate) {
          if (cell.class === 'cell-today') {
            cellClass += 'cell-today ';
          }
          cellClass += 'end-section';
        } else {
          if (cell.class === 'cell-today') {
            cellClass += 'cell-today range-section';
          } else {
            cellClass += 'range-section';
          }
        }
        cell.class = cellClass;
      }
    });
  }

  /**
   * 设置单元格
   *
   * @memberof IbzExpCalendarController
   */
  setCells() {
    if (!this.currentDate) {
      this.currentDate = new Date();
    }
    const dateStr = getDateStr(this.currentDate);
    this.title = dateStr.substr(0, 4) + '年' + dateStr.substr(4, 2) + '月';
    this.cells = generateCells(this.currentDate, this.cells);
    this.selectionChange();
  }

  constructor() {
    this.evt = new QXEvent();
  }
}
